const fs = require('fs')
const path = require('path')
const send = require('koa-send')
const { resolve } = require('path')
const uploadPath = path.join(__dirname, '../upload')

// api/user/info
exports.import = async function(ctx) {
  let metadataFile = ctx.request.files['metadata']; // 获取上传文件

  console.log(ctx.request.files, ctx.request.body)
  // 创建可读流
  const reader = fs.createReadStream(metadataFile.path);
  let filePath = `${uploadPath}/${metadataFile['name']}`;
  // 创建可写流
  const upStream = fs.createWriteStream(filePath);
  // 可读流通过管道写入可写流
  // reader.pipe(upStream);

  const isError = await getFile(reader, upStream); //等待数据存储完成
  
  if (isError) {
    return ctx.body = {
      message: "文件上传失败"
    }
  }

  let content = fs.readFileSync(filePath, 'utf-8')

  return ctx.body = {
      url: `${ctx.request.body.appName} - ${metadataFile.name}`,
      message: "文件上传成功",
      data: metadataFile.type == 'application/json' ? JSON.parse(content.toString()) : content.toString()
  }   
}

function getFile (reader, upStream) {
  return new Promise(function (result) {
    let stream = reader.pipe(upStream); // 可读流通过管道写入可写流
    stream.on('finish', function (err) {
      result(err);
    });
  });
}

exports.list = async function(ctx) {
  let fileList = await getFileList()
  return {
    success: true,
    result: fileList
  }
}

function getFileList() {
  return new Promise((resolve) => {
    fs.readdir(uploadPath, (err, files) => {
      if (err) {
        resolve([])
      } else {
        let fileList = []
        files.forEach(fileName => {
          console.log(fileName)
          let fileDir = path.join(uploadPath, fileName)
          fileList.push(fileName)
          fs.stat(fileDir, (error, stats) => {
            if (error) console.warn('获取文件失败')

            let isFile = stats.isFile()
            let isDir = stats.isDirectory()
            console.log(fileName, isFile)
            if (isFile) {
              // let content = fs.readSync(fileDir, 'utf-8')
              // resolve(content)
            }
            if (isDir) {
              // resolve(getFileList())
            }
          })
        })
        resolve(fileList)
      }

    })
  })
}

exports.name = async function(ctx) {
  let fileName = ctx.params.name
  let dir = path.join(__dirname, '../upload/')

  let content = fs.readFileSync(dir + fileName, 'utf-8')
  let fileExt = fileName.match(/\.(\w+)$/)
  let isJson = fileExt ? (fileExt[1] === 'json') : false

  return {
    success: true,
    data: isJson ? JSON.parse(content.toString()) : content.toString()
  }
}

exports.update = async function(ctx) {
  let body = ctx.request.body
  return {
    success: true,
    body
  }
}